<template>
  <div class="app-container">

    <el-form ref="form" :model="form" label-width="120px">
      <el-tabs type="border-card">
        <el-tab-pane label="基础配置">
          <el-form-item label="商品名称" prop="goods_name" required>
            <el-input v-model="form.goods_name" placeholder="商品名称"/>
          </el-form-item>
          <el-form-item label="分类" prop="category_id" required>
            <SelectedTree
              :tree-data="category_list"
              :default-props="{ children: 'children', label: 'label' }"
              :value="form.category_name"
              :default-expand-all="true"
              @node-click="chooseCategory"
            />
          </el-form-item>
          <el-form-item label="品牌" prop="category_id">
            <SelectedTree
              :tree-data="brand_list"
              :default-props="{ children: 'children', label: 'label' }"
              :value="form.brand_name"
              :default-expand-all="true"
              @node-click="chooseBrand"
            />
          </el-form-item>

          <el-form-item label="商品类型" prop="goods_type">
            <el-radio v-model="form.goods_type" :label="1">普通商品</el-radio>
            <el-radio v-model="form.goods_type" :label="2">虚拟商品</el-radio>
          </el-form-item>
          <el-form-item label="商品服务">
            <el-checkbox-group v-model="form.service">
              <el-checkbox label="7天无理由退换货"></el-checkbox>
              <el-checkbox label="48小时发货"></el-checkbox>
              <el-checkbox label="退货包运费"></el-checkbox>
            </el-checkbox-group>

          </el-form-item>


          <el-form-item label="虚拟销量" prop="sales_fake" required>
            <el-input v-model="form.sales_fake" placeholder="虚拟销量"/>
          </el-form-item>
          <el-form-item label="是否上架" prop="is_on_sale" required>
            <el-switch
              v-model="form.is_on_sale"
              :active-value="1"
              :inactive-value="0"
              @change="(status)=>{form.is_on_sale = status}"
            />
          </el-form-item>
          <el-form-item label="是否首页推荐" >
            <el-switch v-model="form.is_recommend" :active-value="1" :inactive-value="0" @change="(status)=>{form.is_recommend = status}"/>
          </el-form-item>
          <el-form-item label="邮费" prop="shipping_fee" required>
            <el-input v-model="form.shipping_fee" placeholder="邮费"/>
          </el-form-item>
          <el-form-item v-if="form.goods_type==2" label="发货内容" prop="virtual_info">
            <el-input type="textarea" rows="5" v-model="form.virtual_info" placeholder="虚拟商品信息，订单发货需要"/>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="规格配置">
          <el-form-item label="是否开启多规格" prop="is_sku" required>
            <el-switch v-model="form.is_sku" :active-value="1" :inactive-value="0" @change="switchSku"/>
          </el-form-item>
          <div v-if="form.is_sku">
            <sku :initial-skus="form.sku_list" @sku-updated="skuChange"/>
          </div>
          <div v-else>
            <el-form-item label="销售价格" prop="goods_price" required>
              <el-input v-model="form.goods_price" placeholder="商品价格"/>
            </el-form-item>
            <el-form-item label="市场价" prop="market_price" required>
              <el-input v-model="form.market_price" placeholder="市场价"/>
            </el-form-item>
            <el-form-item label="成本价" prop="market_price" required>
              <el-input v-model="form.cost_price" placeholder="成本价"/>
            </el-form-item>
            <el-form-item label="库存" prop="store_count" required>
              <el-input v-model="form.store_count" placeholder="商品库存"/>
            </el-form-item>
          </div>

        </el-tab-pane>
        <el-tab-pane label="商品详情">
          <el-form-item label="商品详情" prop="goods_content" required>
            <ueditor
              ref="ueditor"
              :config="ueConfig"
              :value="form.goods_content"
              @change="form.goods_content = $event"
            />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片">
          <el-form-item label="封面图片" prop="goods_image" required>
            <image-upload
              :file-size="1"
              :is-multiple="false"
              :limit="1"
              :value="form.goods_image"
              :file-type="['png', 'jpg', 'jpeg']"
              @input="afterUpload"
            ></image-upload>
            <el-input v-model="form.goods_image" placeholder="图片"/>
            <span class="el-form-item__info">图片尺寸：400*400</span>
          </el-form-item>
          <el-form-item label="商品图片" prop="goods_image_list" required>
            <el-row :gutter="18">
              <el-col
                :span="3"
                v-for="(image, index) in form.goods_image_list"
                :key="index"
              >
                <div class="preview-item">
                  <img :src="image" alt="商品图片预览" class="preview-image"/>
                </div>
              </el-col>
            </el-row>
            <!-- 商品图片管理器 -->
            <GoodsImageManager
              :value="form.goods_image_list"
              v-model="form.goods_image_list"
              :max-images="6"
              :max-file-size="2"
              :allowed-file-types="['png', 'jpg']"
            />
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="其它配置">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="排序"/>
          </el-form-item>
          <el-form-item label="备注" prop="goods_desc">
            <el-input v-model="form.remark" type="textarea" placeholder="自定义备注，仅限自己可见"/>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item class="action-btn">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import api from '@/api/goods'
import ueditor from '@/components/Ueditor/Ueditor.vue'
import sku from '@/components/goods/sku.vue'
import SelectedTree from '@/components/tools/selectedTree.vue'
import ImageUpload from '@/components/UploadFile/image.vue'
import GoodsImageManager from '@/components/Image/GoodsImageManager.vue'
import { getToken } from '@/utils/auth'
import category from '@/api/category'
import brand from '@/api/brand'

export default {
  components: {
    ueditor, sku, SelectedTree, ImageUpload,
    GoodsImageManager
  },
  data() {
    return {

      category_list: [],
      brand_list: [],
      form: {
        service: ['7天无理由退换货', '48小时发货', '退货包运费'],
        virtual_info: '',
        is_sku: false,
        sku_list: [],
        goods_id: 0,
        goods_name: '',
        goods_price: 0,
        store_count: 0,
        remark: '',
        goods_img: '',
        goods_type: 1,
        is_recommend: 0,
        is_on_sale: 1,
        shipping_fee: 0,
        sort: 0,
        sales_fake: 0,
        sales_num: 0,
        market_price: 0,
        category_id: 0,
        category_name: '',
        brand_id: 0,
        brand_name: '',
        goods_image: '',
        goods_image_list: []

      },
      ueConfig: {
        // 编辑器层级的基数,默认是900
        zIndex: 1000,
        // 编辑器自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 540,
        // 初始容器宽度
        initialFrameWidth: '100%',
        serverUrl: process.env.VUE_APP_BASE_API + '/upload/ueditor/Authorization/' + getToken(),
        // 图片操作的浮层开关
        imagePopup: true,
        // 打开右键菜单功能
        enableContextMenu: true,
        // 是否保持toolbar的位置不动,默认true
        autoFloatEnabled: false,
        // 是否启用元素路径
        elementPathEnabled: false,

        // 当鼠标放在工具栏上时显示的tooltip提示
        labelMap: {
          // simpleupload: '插入图片'
        },
        // 允许的最大字符数
        maximumWords: 10000,
        // 字数统计提示，{#count}代表当前字数，{#leave}代表还可以输入多少字符数,留空支持多语言自动切换，否则按此配置显示
        wordCountMsg: '当前已输入{#count}个字符'
      }
    }
  },

  mounted() {
    if (this.$route.query.hasOwnProperty('goods_id')) {
      this.getData(this.$route.query.goods_id)
    }
    this.getBrandList()
    this.getCategoryList()
  },

  methods: {
    afterUpload(list) {
      if (!list) return
      const file = list[0]
      if (file) {
        this.form.goods_image = file.url
      }
    },
    getBrandList() {
      brand.list_options({}).then((res) => {
        this.brand_list = res.data.list
      })
    },
    getCategoryList() {
      category.list_options({}).then(res => {
        this.category_list = res.data.list
      })
    },
    // 选择分类
    chooseCategory(data) {
      this.form.category_id = data.value
      this.form.category_name = data.label
    },
    chooseBrand(data) {
      this.form.brand_id = data.value
      this.form.brand_name = data.label
    },

    skuChange(sku) {
      console.log(sku)
      this.form.sku_list = sku
    },
    switchSku(e) {
      this.form.is_sku = e
    },
    getData(goods_id) {
      api.info({ goods_id: goods_id }).then((res) => {
        if (res.code === 0) {
          this.form = Object.assign(this.form, res.data)
        }
      })
    },

    onSubmit() {
      const callback = (res) => {
        this.$message({
          type: 'success',
          message: res.msg,
          duration: 500,
          onClose: () => {
            this.$router.go(-1)
          }
        })
      }
      const that = this
      this.$confirm('确定提交吗？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = that.$loading({
          lock: true,
          text: '正在保存',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        if (this.form.goods_id > 0) {
          api.update(this.form).then(res => callback(res)).finally(() => {
            loading.close()
          })
        } else {
          api.create(this.form).then(res => callback(res)).finally(() => {
            loading.close()
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

.editor-content {
  margin-top: 20px;
}

.article-textarea ::v-deep {

textarea {
  padding-right: 40px;
  resize: none;
  border: none;
  border-radius: 0px;
  border-bottom: 1px solid #bfcbd9;
}

}
.action-btn {
  margin-top: 30px;
}

.display-images {
  margin-bottom: 20px;
}

.preview-item {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  height: auto;
  border: 1px solid #ccc;
  margin-bottom: 5px;
}
</style>

